package com.situ.fly.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.fly.entity.Question;
import com.situ.fly.entity.User;
import com.situ.fly.mapper.QuestionMapper;
import com.situ.fly.mapper.UserMapper;
import com.situ.fly.service.QuestionService;

@Service
public class QuestionServiceImpl implements QuestionService{

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private QuestionMapper questionMapper;
	
	
	@Override
	public int add(Question question) {
		// 验证当前用户所拥有的飞吻, 不能超过悬赏的飞吻
		// 查询当前用户的信息
		User user = userMapper.selectById(question.getUid());
		
		if (user.getKiss() < question.getKiss()) {
			// 吻不足
			return -1;
		}
		
		// 添加数据
		return questionMapper.insert(question);
	}

	@Override
	public int edit(Question question) {
		return questionMapper.update(question);
	}

	@Override
	public Question getById(Integer id) {
		return questionMapper.selectById(id);
	}


	@Override
	public List getByUid(Integer uid) {
		return questionMapper.selectByUid(uid);
	}


	@Override
	public int setByField(String field, Integer rank, Integer id) {
		return questionMapper.updateByField(field, rank, id);
	}


	@Override
	public void setViewsnum(Question question, Integer uid) {
		// 如果问题的作者, 是当前登录的用户
		if (uid != -1 && question.getUid()==uid) {
			return ;
		}
		
		// 同一用户浏览数量不能多次计算
		// 需要有一个表, 记录用户的浏览日志
		
		// 游客 计算方式 
		// IP,  Session
		
		
		// 增加一次浏览数量
		question.setViewsnum(question.getViewsnum()+1);
		
		// 写入数据库
		questionMapper.updateViewsnum(question);
	}


	@Override
	public List get(Question question, String order) {
		return questionMapper.select(question, order);
	}
	
	@Override
	public List weekReply(Integer limit) {
		Date now = new Date();
		now.setHours(0);
		now.setMinutes(0);
		now.setSeconds(0);
		
		Date startTime = new Date(now.getTime() - 6*24*60*60*1000);
		return questionMapper.selectByReplyTime(startTime ,limit);
	}
}




